﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.IO;
using Windows.Storage.Pickers;
using Windows.Storage;
using MyVideoManager2.Data;
using Windows.Storage.Streams;
//using System.Management;
using Windows.System.Profile;

namespace MyVideoManager2.Common
{

    //TODO: a completer
    enum extansionFichier
    {
        AVI,
        MP4,
        WMA,
        MKV,
        MPEG, //Ajouté le 03/12/2012 Amor
        FLV   //Pareil
    }

    class AnalyseFichier
    {
        public String cheminDossier { get; set; }
        public String label { get; set; }
        public List<String> lstTitre { get; set; }
        public String lettre { get; set; }
        public String idPeriph { get; set; }
        public List<Peripherique> lstPeripherique { get; set; } // permet de stocké la liste des USB deja analysé   
        public bool nouveauDossier { get; set; } // si il y a un nouveau dossier à analysé, on l'indique

        public AnalyseFichier()
        {
            this.lstTitre = new List<string>();
            this.lstPeripherique = new List<Peripherique>();
            nouveauDossier = false;
        }


        public async Task afficherFolderPicker()
        {

            this.nouveauDossier = false;

            FolderPicker folderPicker = new FolderPicker();
            folderPicker.SuggestedStartLocation = PickerLocationId.Desktop;

            folderPicker.FileTypeFilter.Add(".avi");


            StorageFolder folder = await folderPicker.PickSingleFolderAsync();



            if ( folder != null)
            {
                
                IReadOnlyList<StorageFile> files = await folder.GetFilesAsync();
                
                // on recupere le nom du lecteur
                this.lettre = getLettreCheminDossier(folder.Path);

                // on recupere l'id du periph qui est branché sur le lecteur
                //getIdHardware();


                //TODO: enregistré le numero du perif dans la liste des peripherique deja analysé.

               // Dossier monDossier = new Dossier(folder.Name); //Permet de tout recuperer dans une classe dossier
                //Mediatheque maMediatheque = new Mediatheque();

                foreach (StorageFile file in files)
                {
                    addTitre(file.Name, folder);
                    //monDossier.addFilm(file.Name);
                }
               


                //maMediatheque.addDossier(monDossier);
            }
           

        }

        private String getLettreCheminDossier(String path)
        {
            return path.Substring(0, 1); // on prend la 1er lettre.
        }



        private async void getIdHardware()
        {
            var selector = Windows.Devices.Portable.StorageDevice.GetDeviceSelector();
            var devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(selector);

            foreach (Windows.Devices.Enumeration.DeviceInformation device in devices)
            {
                // Get device root folder
                StorageFolder rootFolder = Windows.Devices.Portable.StorageDevice.FromId(device.Id);
                if (this.lettre.Equals((rootFolder.Path).Substring(0, 1)))
                {

                    this.idPeriph = device.Id;
                }
                
            }
        }

        private string GetHardwareId()
        {
            var token = HardwareIdentification.GetPackageSpecificToken(null);
            var hardwareId = token.Id;
            var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(hardwareId);

            byte[] bytes = new byte[hardwareId.Length];
            dataReader.ReadBytes(bytes);

            return BitConverter.ToString(bytes);
        }
        /*
        private void getIdUSb()
        {
            foreach (ManagementObject drive in new ManagementObjectSearcher("select * from Win32_DiskDrive where InterfaceType='USB'").Get())
            {
                // associate physical disks with partitions

                foreach (ManagementObject partition in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + drive["DeviceID"] + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get())
                {
                   // Console.WriteLine("Partition=" + partition["Name"]);

                    // associate partitions with logical disks (drive letter volumes)

                    foreach (ManagementObject disk in new ManagementObjectSearcher(
                        "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + partition["DeviceID"] + "'} WHERE AssocClass =Win32_LogicalDiskToPartition").Get())
                    {
                        if (disk["Name"].Equals(this.lettre))
                        {
                          ManagementObject usb=  new ManagementObject("Win32_PhysicalMedia.Tag='"+ drive["DeviceID"] + "'");
                            String id=usb["SerialNumber"].ToString();
                          this.lstPeripherique.Add(new Peripherique(id));
                        }
                       // Console.WriteLine("Disk=" + disk["Name"]);
                    }
                }

                // this may display nothing if the physical disk

                // does not have a hardware serial number

               /* Console.WriteLine("Serial="
                 + new ManagementObject("Win32_PhysicalMedia.Tag='"
                 + drive["DeviceID"] + "'")["SerialNumber"]);
                
            }
        }
         * */
        public void filtrageDossier(string chemin)
        {
            /*
            String[] files = Directory.GetFiles("c:\\test");

            for (int i = 0; i < files.Length; i++)
            {
                FileInfo F = new FileInfo(files[i]);
                Console.Out.WriteLine(F.Name);
            } 
             * */
        }

        public void addTitre(String monTitre, StorageFolder folder)
        {
            if(estLisible(monTitre))
            {
                 this.lstTitre.Add(monTitre);
                 cheminDossier = folder.Path;
                 label = folder.Name;
                 this.nouveauDossier = true;
            }
           
        }
        
        /// <summary>
        /// 
        /// Analyse l'extantion
        /// </summary>
        /// <param name="nomFichier"></param>
        /// <returns>True si le fichier est un film.</returns>
        private bool estLisible(string nomFichier)
        {
            int positionPoint = nomFichier.LastIndexOf('.');

            try
            {
                string extansion = nomFichier.Substring(positionPoint+1, nomFichier.Length - positionPoint-1);

                if (extansion != null)
                {
                    if (string.Compare("avi", extansion.ToLower()) == 0)
                    {
                        return true;
                    }
                    else if (string.Compare("mp4", extansion.ToLower()) == 0)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            catch (Exception e)
            {
                return false;
            }
           

         
            


        }



    }
}
